<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<div class="card">
    <div class="card-header">
        <h4 class="mb-0">编辑题目</h4>
    </div>
    <div class="card-body">
        <form id="questionForm">
            <input type="hidden" id="id" name="id" value="${question.id}">
            <div class="mb-3">
                <label for="title" class="form-label">题目标题</label>
                <input type="text" class="form-control" id="title" name="title" value="${question.title}" required>
            </div>
            <div class="mb-3">
                <label for="content" class="form-label">题目内容</label>
                <textarea class="form-control" id="content" name="content" rows="3" required>${question.content}</textarea>
            </div>
            <div class="mb-3">
                <label for="categoryId" class="form-label">分类</label>
                <select class="form-select" id="categoryId" name="categoryId" required>
                    <!-- 分类列表将通过JavaScript动态加载 -->
                </select>
            </div>
            <div class="mb-3">
                <label for="difficulty" class="form-label">难度</label>
                <select class="form-select" id="difficulty" name="difficulty" required>
                    <option value="1">简单</option>
                    <option value="2">中等</option>
                    <option value="3">困难</option>
                </select>
            </div>
            <div class="mb-3">
                <label for="optionA" class="form-label">选项A</label>
                <input type="text" class="form-control" id="optionA" name="optionA" value="${question.optionA}" required>
            </div>
            <div class="mb-3">
                <label for="optionB" class="form-label">选项B</label>
                <input type="text" class="form-control" id="optionB" name="optionB" value="${question.optionB}" required>
            </div>
            <div class="mb-3">
                <label for="optionC" class="form-label">选项C</label>
                <input type="text" class="form-control" id="optionC" name="optionC" value="${question.optionC}" required>
            </div>
            <div class="mb-3">
                <label for="optionD" class="form-label">选项D</label>
                <input type="text" class="form-control" id="optionD" name="optionD" value="${question.optionD}" required>
            </div>
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="isMultiple" name="isMultiple" 
                           ${question.isMultiple ? 'checked' : ''}>
                    <label class="form-check-label" for="isMultiple">
                        多选题
                    </label>
                </div>
            </div>
            <div class="mb-3" id="singleAnswerDiv" style="${question.isMultiple ? 'display:none' : ''}">
                <label class="form-label">正确答案</label>
                <select class="form-select" id="answer" name="answer">
                    <option value="A" ${question.answer eq 'A' ? 'selected' : ''}>A</option>
                    <option value="B" ${question.answer eq 'B' ? 'selected' : ''}>B</option>
                    <option value="C" ${question.answer eq 'C' ? 'selected' : ''}>C</option>
                    <option value="D" ${question.answer eq 'D' ? 'selected' : ''}>D</option>
                </select>
            </div>
            <div class="mb-3" id="multipleAnswerDiv" style="${question.isMultiple ? '' : 'display:none'}">
                <label class="form-label">正确答案（可多选）</label>
                <c:forEach items="A,B,C,D" var="option">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="correctAnswers" 
                               value="${option}" id="correct${option}"
                               ${fn:contains(fn:join(question.correctAnswers,','), option) ? 'checked' : ''}>
                        <label class="form-check-label" for="correct${option}">${option}</label>
                    </div>
                </c:forEach>
            </div>
            <button type="submit" class="btn btn-primary">保存</button>
            <a href="${pageContext.request.contextPath}/admin/question/manage" class="btn btn-secondary">返回</a>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {
    // 加载分类列表
    function loadCategories() {
        $.get('${pageContext.request.contextPath}/admin/category/api/list', function(response) {
            if (response.code === 200) {
                var categories = response.data;
                var options = '<option value="">请选择分类</option>';
                categories.forEach(function(category) {
                    var selected = category.id == ${question.categoryId} ? 'selected' : '';
                    options += '<option value="' + category.id + '" ' + selected + '>' + category.categoryName + '</option>';
                });
                $('#categoryId').html(options);
            }
        });
    }

    // 设置当前难度和答案
    $('#difficulty').val('${question.difficulty}');
    $('#answer').val('${question.answer}');

    // 提交表单
    $('#questionForm').on('submit', function(e) {
        e.preventDefault();
        
        let isMultiple = $('#isMultiple').is(':checked');
        let questionData = {
            id: ${question.id},
            title: $('#title').val(),
            content: $('#content').val(),
            categoryId: $('#categoryId').val(),
            difficulty: $('#difficulty').val(),
            optionA: $('#optionA').val(),
            optionB: $('#optionB').val(),
            optionC: $('#optionC').val(),
            optionD: $('#optionD').val(),
            isMultiple: isMultiple
        };

        if (isMultiple) {
            let selectedAnswers = $('input[name="correctAnswers"]:checked')
                .map(function() { return $(this).val(); }).get();
            if (selectedAnswers.length === 0) {
                alert('请至少选择一个正确答案');
                return;
            }
            questionData.correctAnswers = selectedAnswers;
        } else {
            questionData.answer = $('#answer').val();
        }

        $.ajax({
            url: '${pageContext.request.contextPath}/admin/question/api/update',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(questionData),
            success: function(response) {
                if (response.code === 200) {
                    alert('更新成功');
                    window.location.href = '${pageContext.request.contextPath}/admin/question/manage';
                } else {
                    alert(response.message);
                }
            },
            error: function() {
                alert('更新失败，请稍后重试');
            }
        });
    });

    // 初始化
    loadCategories();
});
</script> 